package com.achilles.fragment;


import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.achilles.bean.DataBean;
import com.achilles.bean.GiftBean;
import com.achilles.bean.ProjectBean;
import com.achilles.database.DBManager;
import com.achilles.playtask.R;
import com.achilles.utils.DateUtils;
import com.achilles.utils.DisplayUtils;
import com.achilles.widget.RevertItemDialog;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class HistoryFragment extends BaseFragment {

    private LinearLayout mLlTodayProject;
    private LinearLayout mLlTodayGift;
    private LinearLayout mLlHistoryCompleteTime;
    private TextView mEmptyProjectTip, mEmptyGiftTip;
    private TextView mProjectScoreTip, mGiftScoreTip;
    private TextView mHistoryCompleteTip;
    private RevertItemDialog mRevertItemDialog;

    private RevertItemDialog.IRevertItemDialogStatus IRevertItemDialogStatus;

    public HistoryFragment() {
        // Required empty public constructor
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_user_info;
    }

    @Override
    protected void onViewCreated(View view) {
        IRevertItemDialogStatus = new RevertItemDialog.IRevertItemDialogStatus() {
            @Override
            public void onDeleteClick(DataBean dataBean) {
                revertData(dataBean);
            }
        };
        mRevertItemDialog = new RevertItemDialog(getActivity());
        mRevertItemDialog.setIRevertItemDialogStatus(IRevertItemDialogStatus);

        int topBottomPadding = (int) DisplayUtils.dp2px(15, getActivity());
        int scoreLeftRightPadding = (int) DisplayUtils.dp2px(15, getActivity());
        int textSize = 17;

        mEmptyProjectTip = new TextView(getActivity());
        mEmptyProjectTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        mEmptyProjectTip.setPadding(0, topBottomPadding, 0, topBottomPadding);
        mEmptyProjectTip.setGravity(Gravity.CENTER);

        mEmptyGiftTip = new TextView(getActivity());
        mEmptyGiftTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        mEmptyGiftTip.setPadding(0, topBottomPadding, 0, topBottomPadding);
        mEmptyGiftTip.setGravity(Gravity.CENTER);

        mProjectScoreTip = new TextView(getActivity());
        mProjectScoreTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        mProjectScoreTip.setPadding(scoreLeftRightPadding, topBottomPadding, scoreLeftRightPadding, topBottomPadding);
        mProjectScoreTip.setGravity(Gravity.END);
        mProjectScoreTip.setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

        mHistoryCompleteTip = new TextView(getActivity());
        mHistoryCompleteTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        mHistoryCompleteTip.setPadding(scoreLeftRightPadding, topBottomPadding, scoreLeftRightPadding, topBottomPadding);
        mHistoryCompleteTip.setGravity(Gravity.CENTER);
        mHistoryCompleteTip.setTextColor(ContextCompat.getColor(getActivity(), R.color.colorPrimary));

        mGiftScoreTip = new TextView(getActivity());
        mGiftScoreTip.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        mGiftScoreTip.setPadding(scoreLeftRightPadding, topBottomPadding, scoreLeftRightPadding, topBottomPadding);
        mGiftScoreTip.setGravity(Gravity.END);
        mGiftScoreTip.setTextColor(ContextCompat.getColor(getActivity(), android.R.color.holo_red_dark));

        mLlTodayProject = (LinearLayout) view.findViewById(R.id.llTodayProject);
        mLlTodayGift = (LinearLayout) view.findViewById(R.id.llTodayGift);
        mLlHistoryCompleteTime = (LinearLayout) view.findViewById(R.id.llHistoryCompleteTime);

        showCompleteData();
    }

    private void revertData(DataBean dataBean) {
        if (dataBean == null) return;
        if (dataBean instanceof ProjectBean) {
            ProjectBean projectBean = (ProjectBean) dataBean;
            int score = projectBean.getProjectScore();
            projectBean.setProjectTimes(0);
            projectBean.setProjectCompleteDate("");
            Log.d("insertOrUpdateProjectDa",projectBean.getProjectCreateTime());
            DBManager.getInstance().insertOrUpdateProjectData(projectBean);
            DBManager.getInstance().updateUserScore(DBManager.getInstance().getScore() - score);
        } else if (dataBean instanceof GiftBean) {
            GiftBean giftBean = (GiftBean) dataBean;
            int score = giftBean.getGiftScore();
            if (giftBean.getGiftType() == GiftBean.GiftType.Single) {
                giftBean.setCompleted(false);
                DBManager.getInstance().insertOrUpdateGiftData(giftBean);
            }
            DBManager.getInstance().updateUserScore(DBManager.getInstance().getScore() + score);
        }
        DBManager.getInstance().deleteHistoryData(dataBean);

        mRevertItemDialog.dismiss();
        showCompleteData();
    }

    private void showCompleteData() {
        String completeDate = String.valueOf(DateUtils.dayBegin(new Date()).getTime());
        List<ProjectBean> projectBeanList = DBManager.getInstance().queryHistoryProjectBeanListByData(true, completeDate);
        List<GiftBean> giftBeanList = DBManager.getInstance().queryHistoryGiftBeanList(true, completeDate);

        Log.d("showCompleteData", "projectBeanList: " + projectBeanList.size() + " giftBeanList: " + giftBeanList.size());
        mLlTodayProject.removeAllViews();
        if (!projectBeanList.isEmpty()) {
            int score = 0;
            Map<Integer, NormalProjectInfo> map = new HashMap<>();
            for (ProjectBean projectBean : projectBeanList) {
                score += projectBean.getProjectScore();
                if (checkAndPutNormalProject(map, projectBean)) {
                    continue;
                }
                mLlTodayProject.addView(generateProjectItem(projectBean));
            }
            for (int key : map.keySet()) {
                mLlTodayProject.addView(generateProjectItem(map.get(key)));
            }
            mProjectScoreTip.setText(getString(R.string.today_project_score_tip, String.valueOf(score)));
            mLlTodayProject.addView(mProjectScoreTip);
        } else {
            mEmptyProjectTip.setText(R.string.no_today_complete_project);
            mLlTodayProject.addView(mEmptyProjectTip);
        }

        mLlTodayGift.removeAllViews();
        if (!giftBeanList.isEmpty()) {
            int score = 0;
            for (GiftBean giftBean : giftBeanList) {
                score += giftBean.getGiftScore();
                mLlTodayGift.addView(generateGiftItem(giftBean));
            }
            mGiftScoreTip.setText(getString(R.string.today_gift_score_tip, String.valueOf(score)));
            mLlTodayGift.addView(mGiftScoreTip);
        } else {
            mEmptyGiftTip.setText(R.string.no_today_complete_gift);
            mLlTodayGift.addView(mEmptyGiftTip);
        }

        mLlHistoryCompleteTime.removeAllViews();
        mHistoryCompleteTip.setText(getString(R.string.history_complete_time_tip,DBManager.getInstance().getHistoryCompleteTime()));
        mLlHistoryCompleteTime.addView(mHistoryCompleteTip);
    }

    private boolean checkAndPutNormalProject(Map<Integer, NormalProjectInfo> map, ProjectBean
            projectBean) {
        if (projectBean.getProjectType() == ProjectBean.ProjectType.Normal) {
            int hashCodeKey = projectBean.getNormalProjectValueHashCode();
            if (!map.containsKey(hashCodeKey)) {
                NormalProjectInfo normalProjectInfo = new NormalProjectInfo(projectBean.getProjectName(),
                        projectBean.getProjectScore(), projectBean.getProjectTotalTimes());
                normalProjectInfo.setNumber(1);
                map.put(hashCodeKey, normalProjectInfo);
            } else {
                NormalProjectInfo normalProjectInfo = map.get(hashCodeKey);
                normalProjectInfo.setNumber(normalProjectInfo.getNumber() + 1);
            }
            return true;
        }
        return false;
    }

    private View generateProjectItem(NormalProjectInfo normalProjectInfo) {
        View projectItemView = LayoutInflater.from(getActivity()).inflate(R.layout.project_list_item, mLlTodayProject, false);
        TextView tvProjectName = (TextView) projectItemView.findViewById(R.id.tvProjectName);
        CheckBox cbProjectComplete = (CheckBox) projectItemView.findViewById(R.id.cbProjectComplete);
        TextView tvCompleteTimeTip = (TextView) projectItemView.findViewById(R.id.tvCompleteTimeTip);
        TextView tvProjectScore = (TextView) projectItemView.findViewById(R.id.tvProjectScore);
        TextView tvProjectType = (TextView) projectItemView.findViewById(R.id.tvProjectType);

        tvProjectName.setText(String.format(getString(R.string.normalProject_group_name),
                normalProjectInfo.getProjectName(), normalProjectInfo.getNumber()));
        cbProjectComplete.setVisibility(View.GONE);
        tvCompleteTimeTip.setText(String.format(getString(R.string.project_complete_time),
                normalProjectInfo.getProjectTotalTime(), normalProjectInfo.getProjectTotalTime()));
        tvProjectScore.setText(String.valueOf("+" + normalProjectInfo.getProjectScore()));
        tvProjectType.setText(R.string.normal_tip);
        projectItemView.setTag(normalProjectInfo);
        return projectItemView;
    }

    private View generateProjectItem(ProjectBean projectBean) {
        View projectItemView = LayoutInflater.from(getActivity()).inflate(R.layout.project_list_item, mLlTodayProject, false);
        TextView tvProjectName = (TextView) projectItemView.findViewById(R.id.tvProjectName);
        CheckBox cbProjectComplete = (CheckBox) projectItemView.findViewById(R.id.cbProjectComplete);
        TextView tvCompleteTimeTip = (TextView) projectItemView.findViewById(R.id.tvCompleteTimeTip);
        TextView tvProjectScore = (TextView) projectItemView.findViewById(R.id.tvProjectScore);
        TextView tvProjectType = (TextView) projectItemView.findViewById(R.id.tvProjectType);

        tvProjectName.setText(projectBean.getProjectName());
        cbProjectComplete.setVisibility(View.GONE);
        tvCompleteTimeTip.setText(String.format(getString(R.string.project_complete_time), projectBean.getProjectTimes(), projectBean.getProjectTotalTimes()));
        tvProjectScore.setText(String.valueOf("+" + projectBean.getProjectScore()));
        if (projectBean.getProjectType() == ProjectBean.ProjectType.EveryWeek) {
            tvProjectType.setText(getString(R.string.everyWeek_number_tip));
        } else if (projectBean.getProjectType() == ProjectBean.ProjectType.EveryMonth) {
            tvProjectType.setText(getString(R.string.everyMonth_number_tip));
        } else {
            tvProjectType.setVisibility(View.GONE);
        }
        projectItemView.setTag(projectBean);
        projectItemView.setOnLongClickListener(new OnItemLongClick());
        return projectItemView;
    }

    private View generateGiftItem(GiftBean giftBean) {
        View giftItemView = LayoutInflater.from(getActivity()).inflate(R.layout.gift_list_item, mLlTodayGift, false);
        TextView tvGiftName = (TextView) giftItemView.findViewById(R.id.tvGiftName);
        TextView tvGiftScore = (TextView) giftItemView.findViewById(R.id.tvGiftScore);

        tvGiftName.setText(giftBean.getGiftName());
        tvGiftScore.setText(String.valueOf("-" + giftBean.getGiftScore()));
        giftItemView.setTag(giftBean);
        giftItemView.setOnLongClickListener(new OnItemLongClick());
        return giftItemView;
    }

    public static HistoryFragment getInstance() {
        return new HistoryFragment();
    }

    class NormalProjectInfo {
        private int number;
        private String projectName;
        private int projectScore;
        private int projectTotalTime;

        public NormalProjectInfo(String projectName, int projectScore, int projectTotalTime) {
            this.projectName = projectName;
            this.projectScore = projectScore;
            this.projectTotalTime = projectTotalTime;
        }

        public String getProjectName() {
            return projectName;
        }

        public int getProjectScore() {
            return projectScore;
        }

        public int getProjectTotalTime() {
            return projectTotalTime;
        }

        public void setNumber(int number) {
            this.number = number;
        }

        public int getNumber() {
            return number;
        }
    }

    class OnItemLongClick implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View v) {
            DataBean dataBean = (DataBean) v.getTag();
            mRevertItemDialog.show(dataBean);
            return true;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            showCompleteData();
        }
    }
}
